//
//  AddressManager.m
//  YYPHSpeedJump
//
//  Created by sujiang on 15/12/22.
//  Copyright © 2015年 sujiang. All rights reserved.
//

#import "AddressManager.h"
#import "AddressCell.h"
#import "AddressEditViewController.h"

@interface AddressManager ()<UITableViewDelegate, UITableViewDataSource>
{
   
    
}

@end

@implementation AddressManager

- (void)viewWillAppear:(BOOL)animated
{
    [self requestData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubViews];
    self.title = @"地址管理";
}
- (void)requestData
{
    NSDictionary *dic = @{@"u":[[NSUserDefaults standardUserDefaults]objectForKey:@"user_id"]};
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kBaseUrl,kAddressUrl];
    [NetworkHandle getUpDataWithUrl:urlStr class:NSClassFromString(@"AddressModel") dictionary:dic firstKey:@"data" success:^(NSArray *array) {
        self.dataArray = [NSMutableArray arrayWithArray:array];
        [self.tableView reloadData];
    }];
    
}
- (void)addSubViews
{
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStyleGrouped)];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"AddressCell" bundle:nil] forCellReuseIdentifier:@"AddressCell"];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 75 * kHeightScale)];
    footerView.backgroundColor = kColors(239, 239, 241, 1);
    
    UIButton *addBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    addBtn.frame = CGRectMake(21, 0, footerView.width - 42, 44);
    [addBtn setTitle:@"新增地址" forState:(UIControlStateNormal)];
    addBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [addBtn setTitleColor:kColors(255, 255, 255, 1) forState:(UIControlStateNormal)];
    addBtn.backgroundColor = kColors(218, 166, 46, 1);
    [footerView addSubview:addBtn];
    addBtn.layer.cornerRadius = 5;
    self.tableView.tableFooterView = footerView;
    [addBtn addTarget:self action:@selector(actionAddAddress:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataArray.count == 0) {
        return 0;
    }
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 && self.dataArray.count == 0) {
        return 80;
    }
    return 8;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 105;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddressCell" forIndexPath:indexPath];
    
    cell.model = self.dataArray[indexPath.row];
    [cell.setDefaultAddBtn addTarget:self action:@selector(actionSetDefault:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.setDefaultAddBtn.tag = 1000 + indexPath.row;
    
    [cell.editBtn addTarget:self action:@selector(actionEditBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.editBtn.tag = 10 + indexPath.row;
    
    [cell.deleteBtn addTarget:self action:@selector(actionDeleteBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.deleteBtn.tag = 100 + indexPath.row;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0 && self.dataArray.count == 0) {
        UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
        UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, kScreenWidth - 40, 60)];
        lable.font = [UIFont systemFontOfSize:24];
        lable.text = @"请添加收货地址!";
        lable.textColor = kColors(218, 166, 46, 1);
        [aView addSubview:lable];
        lable.textAlignment = NSTextAlignmentCenter;
        return aView;
        
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.deal_id == nil) {
        return;
    }
    AddressModel *model = self.dataArray[indexPath.row];
    NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, kSetAddr];
    NSDictionary *dict = @{@"u":[[NSUserDefaults standardUserDefaults]objectForKey:@"user_id"], @"deal_id":self.deal_id, @"address_id":model.address_id};
    [NetworkHandle getInfoWithUrl:string dictionary:dict success:^(NSDictionary *dictionary) {
        if ([dictionary[@"code"] isEqualToString:@"200"]) {
            [self.navigationController popViewControllerAnimated:YES];
            self.changeAddr(model);
        } else {
            [Tools showAlert:dictionary[@"message"]];
        }
    }];
}

#pragma mark -- 按钮点击事件
// 设置默认地址
- (void)actionSetDefault:(UIButton *)button
{
    AddressModel *model = self.dataArray[button.tag - 1000];

    NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, @"/user.do?cmd=set_default_addr"];
    NSDictionary *dic = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"address_id":model.address_id};
    // /user.do?cmd=set_default_addr&u=X&address_id=X
    NSIndexPath *path = [NSIndexPath indexPathForRow:button.tag - 1000 inSection:0];
    AddressCell *thisCell = [self.tableView cellForRowAtIndexPath:path];
    NSArray *array = [self.tableView visibleCells];
    
    for (AddressCell *cell in array) {
        if (cell == thisCell) {
            [NetworkHandle getInfoWithUrl:string dictionary:dic success:^(NSDictionary *dictionary) {
                if ([dictionary[@"code"] isEqualToString:@"200"]) {
                    [cell.setDefaultAddBtn setBackgroundImage:[UIImage imageNamed:@"xz"] forState:(UIControlStateNormal)];
                } else {
                    [Tools showAlert:dictionary[@"message"]];
                }
                
            }];
 
        } else {
            [cell.setDefaultAddBtn setBackgroundImage:[UIImage imageNamed:@"wxz"] forState:(UIControlStateNormal)];
        }
    }
    
}
// 编辑
- (void)actionEditBtn:(UIButton *)button
{
    AddressEditViewController *editVC = [[AddressEditViewController alloc] init];
    [self.navigationController pushViewController:editVC animated:YES];
    editVC.model = self.dataArray[button.tag - 10];
    editVC.judg = @"edit";
}
// 删除
- (void)actionDeleteBtn:(UIButton *)button
{
    AddressModel *model = self.dataArray[button.tag - 100];
    NSDictionary *dic = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"address_id":model.address_id};
    NSString *url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kAddressDele];
    [NetworkHandle getInfoWithUrl:url dictionary:dic success:^(NSDictionary *dictionary) {
       // NSLog(@"%@", dictionary);
        if ([dictionary[@"code"] isEqualToString:@"200"]) {
            [self.dataArray removeObject:model];
            [self.tableView reloadData];
        } else {
            [Tools showAlert:dictionary[@"message"]];
        }
    }];
}
// 新增地址
- (void)actionAddAddress:(UIButton *)button
{
    AddressEditViewController *editVC = [[AddressEditViewController alloc] init];
    [self.navigationController pushViewController:editVC animated:YES];
    editVC.judg = @"add";
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
